package com.rq.download_okhttp;

import android.app.Activity;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import androidx.annotation.Nullable;
import androidx.core.content.FileProvider;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 下载服务
 * 1.继承IntentService 是因为读写文件比较耗时，且还要进行下载，所以用另开子线程的Service
 * 1.启动apk下载
 * 2.创建通知栏显示下载进度
 * <p>
 * <service android:name="com.rq.download_okhttp.DownloadIntentService" />
 */
public class DownloadIntentService extends IntentService {


    public static Intent getTask(Context context, String url, String saveName, DownloadListener listener) {
        DownloadUtil.setContext(context);
        Intent intent = new Intent(context, DownloadIntentService.class);
        intent.putExtra("download_url", url);
        intent.putExtra("apk_id", saveName);
        if (listener != null)
            mDownloadCallBack.add(listener);
        DownloadUtil.setUrl(url);
        Log.e("DownloadIntentService", "getTask.url:" + url);
        Log.e("DownloadIntentService", "getTask.saveName:" + saveName);
        return intent;
    }

    private static final String TAG = "DownloadIntentService";
    public static String DOWNLOAD_DIR;  //下载目录
    private static List<DownloadListener> mDownloadCallBack = new ArrayList<>();
    private NotificationManager mNotifyManager;
    private int downloadId = 10;
    private String mDownloadFileName;

    public DownloadIntentService() {
        super("DownloadService");
        DOWNLOAD_DIR = DownloadUtil.getSaveDir() + "/download/";
        File file = new File(DOWNLOAD_DIR);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    static void removeDownloadCallBack(DownloadListener lis) {
        mDownloadCallBack.remove(lis);
    }

    static void addDownloadCallBack(DownloadListener lis) {
        mDownloadCallBack.add(lis);
    }

    Handler mainHandler = new Handler(Looper.getMainLooper());

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        if (intent == null || intent.getExtras() == null) {
            return;
        }
        //下载地址
        String downloadUrl = intent.getExtras().getString("download_url");
        String vNumber = intent.getExtras().getString("apk_id");
        //文件名
        if (vNumber.endsWith("apk")) {
            mDownloadFileName = vNumber;//intent.getExtras().getString("download_file");
        } else {
            mDownloadFileName = vNumber + ".apk";//intent.getExtras().getString("download_file");
        }
        Log.d(TAG, "下载地址:" + downloadUrl);
        Log.d(TAG, "文件名:" + mDownloadFileName);
        Log.d(TAG, "保存地址:" + DOWNLOAD_DIR);
        if (!new File(DownloadIntentService.DOWNLOAD_DIR).exists()) {
            new File(DownloadIntentService.DOWNLOAD_DIR).mkdirs();
        }
        //1.判断文件是否存在，具提的下载进度，如果已下载完成，则执行安装
        final File file = new File(DownloadIntentService.DOWNLOAD_DIR + mDownloadFileName);
        long range = 0;
        int progress = 0;
        if (file.exists()) {
            //文件存在，找到文件已下载多少KB，计算下载进度
            //用路径作为key不妥，后台可能设置各个版本下载链接是一样的。所以用apk版本名合适一些
            range = SPDownloadUtil.getInstance().get(mDownloadFileName, 0);
            progress = (int) (range * 100 / Math.max(1, file.length()));
            //判断是否已下载完整
            if (range == file.length()) {
                if (mDownloadCallBack != null) {
                    for (DownloadListener downloadListener : mDownloadCallBack) {
                        downloadListener.onProgress(progress);
                        if (progress == 100) {
                            downloadListener.onCompleted(file);
                        }
                    }

                }
                return;
            }
        }
        final Notification.Builder builder = new Notification.Builder(DownloadUtil.getCtx());
        builder.setSmallIcon(DownloadUtil.getDownIconRes())
                .setTicker("正在下载")//设置点击后取消Notification
                .setContentTitle("正在下载")//设置点击后取消Notification
                .setProgress(100, progress, false);
        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotifyManager.notify(downloadId, builder.build());
        //3.下载apk
        DownloadRetrofitUtils.getInstance()
                .downloadFile(this, range, downloadUrl, mDownloadFileName, new DownloadCallBack() {
                    @Override
                    public void onProgress(final int progress) {
                        Log.d("DownloadIntentService", "已下载" + progress + "%");
                        builder.setContentTitle("已下载" + progress + "%")
                                .setProgress(100, progress, false);
                        mNotifyManager.notify(downloadId, builder.build());
                        if (mDownloadCallBack != null) {
                            mainHandler.post(new Runnable() {
                                @Override
                                public void run() {
                                    for (DownloadListener downloadListener : mDownloadCallBack) {
                                        downloadListener.onProgress(progress);
                                    }
                                }
                            });
                        }
                    }

                    @Override
                    public void onCompleted() {
                        Log.d(TAG, "下载完成");
                        mNotifyManager.cancel(downloadId);
                        if (mDownloadCallBack != null) {
                            for (DownloadListener downloadListener : mDownloadCallBack) {
                                downloadListener.onCompleted(file);
                            }
                        }
                    }

                    @Override
                    public void onError(String msg) {
                        if (mDownloadCallBack != null) {
                            for (DownloadListener downloadListener : mDownloadCallBack) {
                                downloadListener.onError();
                            }
                        }
                        Log.d(TAG, "下载发生错误--" + msg);
                        mNotifyManager.cancel(downloadId);
                    }
                });
    }


    public interface DownloadListener {
        void onProgress(int progress);

        void onCompleted(File file);

        void onError();
    }

}